package com.sfy.sfypicturebackend.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sfy.sfypicturebackend.annotation.AuthCheck;
import com.sfy.sfypicturebackend.common.BaseResponse;
import com.sfy.sfypicturebackend.common.DeleteRequest;
import com.sfy.sfypicturebackend.common.ErrorCode;
import com.sfy.sfypicturebackend.common.ResultUtils;
import com.sfy.sfypicturebackend.constant.UserConstant;
import com.sfy.sfypicturebackend.exception.BusinessException;
import com.sfy.sfypicturebackend.exception.ThrowUtils;
import com.sfy.sfypicturebackend.manager.cache.CaffeineCacheTemplate;
import com.sfy.sfypicturebackend.manager.cache.RedisCacheTemplate;
import com.sfy.sfypicturebackend.model.dto.file.UploadPictureBatchRequest;
import com.sfy.sfypicturebackend.model.dto.picture.*;
import com.sfy.sfypicturebackend.model.entity.Picture;
import com.sfy.sfypicturebackend.model.entity.PictureTagCategory;
import com.sfy.sfypicturebackend.model.entity.User;
import com.sfy.sfypicturebackend.model.enums.PictureReviewStatusEnum;
import com.sfy.sfypicturebackend.model.vo.picture.PictureVO;
import com.sfy.sfypicturebackend.service.PictureService;
import com.sfy.sfypicturebackend.service.UserService;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RequestMapping("/picture")
@RestController
public class PictureController {

    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Resource
    private RedisCacheTemplate redisCacheTemplate;

    @Resource
    private CaffeineCacheTemplate caffeineCacheTemplate;

    /**
     * 上传图片（可重新上传）
     */
    @PostMapping("/upload")
    //@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }


    /**
     * 删除图片
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest,
                                               HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        Picture pictureById = pictureService.getById(id);
        // 只有本人和管理员能删除
        if (!pictureById.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
        }
        boolean res = pictureService.removeById(id);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 更新图片(仅管理员)
     *
     * @param pictureUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest
            , HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        pictureService.validPicture(picture);
        // 判断是否存在
        Long id = picture.getId();
        Picture pictureServiceById = pictureService.getById(id);
        if (pictureServiceById == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture, loginUser);
        // 修改
        boolean res = pictureService.updateById(picture);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取图片(仅管理员)
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
        }
        Picture pictureServiceById = pictureService.getById(id);
        return ResultUtils.success(pictureServiceById);
    }

    /**
     * 根据id获取图片VO
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(id);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表(封装类)
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        // 普通用户只能查看过审的图片
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 编辑图片（给用户使用）
     *
     * @param pictureEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest,
                                             HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        pictureService.editPicture(pictureEditRequest, request);
        return ResultUtils.success(true);
    }

    /**
     * 获取标签分类 TODO
     *
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }


    /**
     * 图片审核功能
     *
     * @param pictureReviewRequest
     * @param request
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest
            , HttpServletRequest request) {
        pictureService.doPictureReview(pictureReviewRequest, userService.getLoginUser(request));
        return ResultUtils.success(true);
    }


    /**
     * 批量抓取图片
     * @param uploadPictureBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureBatch(@RequestBody UploadPictureBatchRequest uploadPictureBatchRequest
            , HttpServletRequest request) {
        ThrowUtils.throwIf(uploadPictureBatchRequest == null,ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Integer res = pictureService.uploadPictureBatch(uploadPictureBatchRequest, loginUser);
        return ResultUtils.success(res);
    }


    /**
     * 分页获取图片列表(封装类,Redis缓存)
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo/cache/redis")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithRedisCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                           HttpServletRequest request) {
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        // 构建缓存
        String key = redisCacheTemplate.buildCache(pictureQueryRequest);
        // 查询缓存
        String value = redisCacheTemplate.getFromCache(key);
        if (value != null) {
            // 说明缓存命中了
            Page<PictureVO> cacheValue = JSONUtil.toBean(value, Page.class);
            return ResultUtils.success(cacheValue);
        }
        // 普通用户只能查看过审的图片
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize),
                pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 存入缓存中
        redisCacheTemplate.putToCache(pictureVOPage, key);
        return ResultUtils.success(pictureVOPage);
    }


    /**
     * 分页获取图片列表(封装类,本地缓存)
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo/cache/caffeine")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCaffeineCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                              HttpServletRequest request) {
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        // 构建缓存
        String key = caffeineCacheTemplate.buildCache(pictureQueryRequest);
        // 查询缓存
        String value = caffeineCacheTemplate.getFromCache(key);
        if (value != null) {
            // 说明缓存命中了
            Page<PictureVO> cacheValue = JSONUtil.toBean(value, Page.class);
            return ResultUtils.success(cacheValue);
        }
        // 普通用户只能查看过审的图片
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize),
                pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 存入缓存中
        caffeineCacheTemplate.putToCache(pictureVOPage, key);
        return ResultUtils.success(pictureVOPage);
    }


    /**
     * 分页获取图片列表(封装类,多级缓存)
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo/cache/level")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithLevelCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                           HttpServletRequest request) {
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        String key = redisCacheTemplate.buildCache(pictureQueryRequest);
        // 查询本地缓存
        String value = caffeineCacheTemplate.getFromCache(key);
        if (value != null) {
            // 说明缓存命中了
            Page<PictureVO> cacheValue = JSONUtil.toBean(value, Page.class);
            return ResultUtils.success(cacheValue);
        }
        // 查询分布式缓存
        value = redisCacheTemplate.getFromCache(key);
        if (value != null) {
            Page<PictureVO> cacheValue = JSONUtil.toBean(value, Page.class);
            // 说明缓存命中了
            caffeineCacheTemplate.putToCache(cacheValue, value);
            return ResultUtils.success(cacheValue);
        }
        // 普通用户只能查看过审的图片
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize),
                pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        String jsonStr = JSONUtil.toJsonStr(pictureVOPage);
        // 存入本地缓存中
        caffeineCacheTemplate.putToCache(pictureVOPage, key);
        // 存入分布式缓存中
        redisCacheTemplate.putToCache(pictureVOPage, key);
        return ResultUtils.success(pictureVOPage);
    }


    @PostMapping("/clear/cache")
    public BaseResponse<Boolean> clearCache(@RequestBody PictureQueryRequest pictureQueryRequest){
        // 查询key
        String key = redisCacheTemplate.buildCache(pictureQueryRequest);
        // 清除key
        redisCacheTemplate.clearCache(key);
        caffeineCacheTemplate.clearCache(key);
        return ResultUtils.success(true);
    }
}
